package com.algorithm5;

import java.util.Arrays;

public class BubbleSort {
    public static void sort(int[] array){
        //冒泡排序:两两比较，大的往后排。
        //循环的次数,循环arrray.length-1次
        for(int j=0;j<array.length-1;j++){
            //循环比较当前和后一个的值，让大的往后排
            boolean hasChanged = false;
            for(int k=1;k<array.length-j;k++){
                if(array[k-1]>array[k]){
                    swap(array,k,k-1);
                    hasChanged = true;
                }
            }
            if(!hasChanged){
                return;
            }
            System.out.println("j="+j+"-->"+ Arrays.toString(array));
        }

    }

    public static void swap(int[] array,int i,int j){
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    public static void main(String[] args){
        int[] array = new int[]{4,3,6,8,9,7,10,5,1,2};
        System.out.println("array:"+ Arrays.toString(array));
        sort(array);
        System.out.println("sorted array:"+ Arrays.toString(array));

    }
}
